<template>
  <div style="padding-bottom: 60px">
    <div class="flex-center-between mb14 mt24">
      <a-alert message="请仔细检查确保以下签署方信息" banner closable />
    </div>
    <!-- 加载效果 -->
    <div v-if="clicked" class="example">
      <a-spin size="large" style="color: #6a66f6" />
    </div>
    <a-table :columns="contractColumns" :data-source="contractlist" row-key="id">
      <span slot="contractName" slot-scope="text, record">
        {{ record.name + "的" + category.name }}
      </span>
      <span slot="contractNo" slot-scope="text, record">
        {{ record.contractNo ? record.contractNo : "--" }}
        <a-icon type="form" style="color: #e8e8e8; font-size: 18px; margin-left: 10px" @click="updateContactNumber(record)" />
      </span>
      <span slot="action" slot-scope="text, record">
        <a @click="preview(record)">预览</a>
      </span>
    </a-table>
    <div
      class="btnline bgc-white"
      :style="{
        position: 'fixed',
        width: 'auto',
        bottom: fixedBottom,
        right: '24px',
        zIndex: '10',
        left: fixedLeft
      }"
    >
      <a-button type="text" @click="backStep">上一步</a-button>
      <a-button :disabled="clicked" type="primary" @click="confirmSign">发起签署</a-button>
    </div>
    <!-- 编辑合同编号 -->
    <a-modal
      title="编辑合同编号"
      :visible="updateVisible"
      :confirm-loading="confirmLoading"
      @ok="confirmUpdateContactNumber"
      @cancel="handleCancel"
    >
      <div>
        <a-form :form="updateForm" :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }" :colon="true">
          <a-form-item label="合同编号">
            <a-input v-decorator="['contractNo', { rules: [{ required: true, message: '请输入' }] }]" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <!-- 预览合同 -->
    <a-modal
      title="合同预览"
      :confirm-loading="confirmLoading"
      :visible="detailVisible"
      class="ht ql-editor-wrapper"
      width="900px"
      destroy-on-close
      @ok="detailVisible = false"
      @cancel="detailVisible = false"
    >
      <h3 class="mb16">{{ currentContract.name + "的" + category.name }}</h3>
      <div class="ql-editor-content" style="height: auto; padding-right: 0; padding-left: 0">
        <div class="editor-main" style="padding-top: 0">
          <div
            :style="{
              width: `${a4_width}px`,
              position: 'relative',
              margin: '0 auto'
            }"
          >
            <pdf v-if="src" ref="pdf" :src="src" :page="currentPage" @num-pages="pageCount = $event" @page-loaded="currentPage = $event" />
            <template v-for="item in dropList">
              <vue-draggable-resizable
                v-if="item.page === currentPage"
                :ref="`${item.type}${item.id}`"
                :key="item.id"
                :parent="true"
                :resizable="false"
                :w="seal_size"
                :h="seal_size"
                :x="item.x"
                :y="item.y"
                :draggable="false"
                class-name="editor-main-drag"
              >
                <div v-if="item.type === 'seal'">
                  <img src="../../../../assets/img/seal-circle.png" alt="" />
                </div>
                <div v-if="item.type === 'sign'">
                  <div class="editor-main-drag-sign">电子签名</div>
                </div>
                <div v-if="item.type === 'holder'">
                  <div class="editor-main-drag-sign lp">法人章</div>
                </div>
              </vue-draggable-resizable>
            </template>
          </div>
        </div>
      </div>
      <div class="editor-config" style="padding: 0; width: 70px; bottom: 77px; right: 24px; border-left: none">
        <div class="editor-config-page" style="display: flex; flex-direction: row">
          <div class="editor-config-page-btn mr8" style="margin-bottom: 0" @click="pageUp">
            <a-icon type="up" />
          </div>
          <div class="editor-config-page-btn" style="margin-bottom: 0" @click="pageDown">
            <a-icon type="down" />
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script>
// 设定 A4 尺寸为 795 * 1125，印章大小为 159 * 159
const A4_WIDTH = 816;
const A4_HEIGHT = 1156;
const SEAL_SIZE = 159;
const HALF_SEAL_SIZE_ARR = [0, 80, 80, 50];
const FIX_SEAL_SIZE_ARR = [0, 40, 110, 80];
import { publishTemplateSignReq, templateSealListAllReq, templateDetailReq, getCategoriesDetail } from "@/api/company/contract";
import { isContainByString } from "@/utils/index";
import { getToken } from "xqjr-module-auth";
import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";
import pdf from "vue-pdf";
import moment from "moment"; // 导入文件
import axios from "axios";
import { mapGetters } from "vuex";
const contractColumns = [
  {
    title: "文件名称",
    dataIndex: "contractName",
    scopedSlots: { customRender: "contractName" }
  },
  {
    title: "员工签署方",
    dataIndex: "name"
  },
  {
    title: "操作",
    dataIndex: "action",
    scopedSlots: { customRender: "action" }
  }
];
export default {
  components: {
    pdf
  },
  props: {
    contractlist: {
      type: Array,
      required: true
    },
    contractinfo: {
      type: Object,
      required: true
    },
    templateId: {
      type: Number,
      required: true
    },
    variableListMap: {
      type: Array,
      required: true
    },
    isCheckFace: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      dropList: [],
      name: "",
      content: "",
      currentPage: 1,
      pageCount: 0,
      src: null,
      a4_width: A4_WIDTH,
      a4_height: A4_HEIGHT,
      seal_size: SEAL_SIZE,
      isContainByString,
      contractColumns,
      detailVisible: false,
      updateVisible: false,
      confirmLoading: false,
      clicked: false,
      updateForm: this.$form.createForm(this, { name: "updateForm" }),
      contractNo: "",
      companyId: "",
      template: {},
      category: {},
      partyAName: "",
      currentContract: "",
      htmlContent: "",
      enterpriseContract: {},
      companyName: this.$store.state.hr.companyName
    };
  },
  computed: {
    ...mapGetters(["permissions_menu_urls"]),
    fixedLeft() {
      const isOpened = this.$store.state.app.sidebar.opened;
      return `${isOpened ? 210 + 24 : 64 + 24}px`;
    },
    fixedBottom() {
      const mainWidth = this.$store.state.app.mainWidth;
      const isOpened = this.$store.state.app.sidebar.opened;
      const contentWidth = mainWidth - (isOpened ? 210 : 64) - 48;
      const isScrolling = contentWidth < 1000;
      return `${isScrolling ? 9 + 24 : 24}px`;
    }
  },
  watch: {
    contractlist(val) {},
    pageCount(val) {
      if ((!!val || val === 0) && !this.loading) {
        this.loadTemplateSeals();
      }
    }
  },
  created() {
    this.companyId = this.$store.state.hr.companyId;
    this.getCategoriesDetail(this.contractinfo.id);
    this.getDetailByTemplateId(this.templateId);
    this.siteList = this.$store.state.auth.permissions.siteList;
    var partyA = this.siteList.find((item) => item.currSite === true);
    this.partyAName = partyA.name;
  },
  methods: {
    loadTemplate() {
      templateDetailReq(this.templateId)
        .then((res) => {
          this.categoryId = res.data.categoryId;
          this.name = res.data.name;
          this.content = res.data.content;
          this.$nextTick(() => {
            this.loadTemplatePdf();
          });
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    pageUp() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    pageDown() {
      if (this.currentPage < this.pageCount) {
        this.currentPage++;
      }
    },
    loadTemplatePdf() {
      axios({
        url: "/contract/api/v1/templates/preview",
        method: "post",
        responseType: "blob",
        headers: {
          token: getToken()
        },
        data: {
          fileName: this.name,
          content: this.content,
          variableList: this.currentContract.conVariableMap
        }
      })
        .then(async (res) => {
          const urlObj = URL.createObjectURL(new Blob([res.data], { type: "application/pdf" }));
          this.src = pdf.createLoadingTask({ url: urlObj, CMapReaderFactory });
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    loadTemplateSeals() {
      this.loading = true;
      templateSealListAllReq(this.templateId, this.$route.meta.pageType)
        .then((res) => {
          this.dropList = res.data.map((item) => ({
            id: item.id,
            page: item.sealPage > this.pageCount ? this.pageCount : item.sealPage,
            x: (item.sealPositionX / 612) * this.a4_width - HALF_SEAL_SIZE_ARR[item.accountType],
            y: this.a4_height - FIX_SEAL_SIZE_ARR[item.accountType] - (item.sealPositionY / 792) * this.a4_height,
            type: this.transType(item.accountType, item.type)
          }));
          this.oldSealIdList = this.dropList.map((item) => item.id);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    transType(aType, type) {
      if (aType === 1) {
        return type === 1 ? "sign" : "sign_date";
      } else if (aType === 2) {
        return type === 1 ? "seal" : "seal_date";
      } else if (aType === 3) {
        return "holder";
      } else {
        return "";
      }
    },
    initContractList() {
      this.contractlist.forEach((item) => {
        item.contractName = this.contractinfo.name + "-" + item.name;
        let content = this.template.content;
        const varibleKeys = content.match(/#[\u4e00-\u9fa5]+#/g);
        const varibles = item.conVariableMap;
        if (varibleKeys) {
          varibleKeys.map((key) => {
            const keyTemp = key.replace(/#/g, "");
            const idx = varibles.findIndex((item) => {
              return item[keyTemp];
            });
            if (idx > -1) {
              if (varibles[idx][keyTemp]["content"]) {
                content = content.replace(new RegExp(`#${this.tranHanzi(keyTemp)}#`, "g"), varibles[idx][keyTemp]["content"]);
              } else {
                content = content.replace(new RegExp(`#${this.tranHanzi(keyTemp)}#`, "g"), " ");
              }
            } else {
              item.templateContent = content;
            }
          });
        } else {
          item.templateContent = content;
        }
        // }
        item.templateContent = content;
      });
    },
    getDetailByTemplateId(id) {
      templateDetailReq(id).then((res) => {
        this.template = res.data;
        this.initContractList();
      });
    },
    tranHanzi(str) {
      // TODO模板变量颜色替换字符串 style="color: rgb(106, 102, 246);
      return escape(str).toLocaleLowerCase().replace(/%u/gi, "\\u");
    },
    getCategoriesDetail(categoryId) {
      getCategoriesDetail(categoryId).then((res) => {
        this.category = res.data;
      });
    },
    handleCancel() {
      this.updateVisible = false;
      this.updateForm.resetFields();
    },
    preview(record) {
      this.currentContract = record;
      this.currentPage = 1;
      this.detailVisible = true;
      this.loadTemplate();
    },
    updateContactNumber(record) {
      this.updateVisible = true;
      this.currentContract = record;
      if (record.contractNo) {
        setTimeout(() => {
          this.updateForm.setFieldsValue({
            contractNo: record.contractNo
          });
        }, 100);
      } else {
        setTimeout(() => {
          this.updateForm.setFieldsValue({
            contractNo: ""
          });
        }, 100);
      }
      this.updateForm.resetFields();
    },
    confirmUpdateContactNumber(e) {
      var that = this;
      e.preventDefault();
      this.updateForm.validateFields((err, values) => {
        if (!err) {
          that.contractNo = values;
          that.contractlist.forEach((item, index) => {
            if (item.empId === that.currentContract.empId) {
              item.contractNo = values.contractNo;
              this.updateVisible = false;
              this.$set(this.contractlist, index, item);
            }
          });
        }
      });
    },
    confirmSign() {
      this.clicked = true;
      var memberVariableListGroup = [];
      var contractTemplist = this.contractlist;
      contractTemplist.forEach((item) => {
        if (item.userId) {
          if (item.contractEndTime !== null && item.contractEndTime !== "") {
            item.contractEndTime = new Date(moment(item.contractEndTime).format("YYYY-MM-DD"));
          }
          if (item.contractStartTime != null && item.contractStartTime !== "") {
            item.contractStartTime = new Date(moment(item.contractStartTime).format("YYYY-MM-DD"));
          }
          var memberVariableList = {
            accountType: 1,
            contractName: item.contractName,
            fileName: item.name + this.category.name,
            memberId: item.userId,
            contractNo: item.contractNo,
            variableList: item.conVariableMap,
            partyAName: this.partyAName,
            partyBName: item.name,
            partyBPhone: item.phone,
            endDate: item.contractEndTime ? moment(item.contractEndTime).format("YYYY-MM-DD") : "",
            publishDate: item.contractStartTime ? moment(item.contractStartTime).format("YYYY-MM-DD") : "",
            dateline: item.timelimitType === 1 ? item.contractExpire * 12 : item.contractExpire,
            contractType: item.contractType
          };
          memberVariableListGroup.push(memberVariableList);
        }
      });
      var publishSignDTO = {
        categoryId: this.category.id,
        templateId: this.templateId,
        subjectId: this.isContainByString("contractAdmin") ? "0" : this.companyId,
        memberVariableList: memberVariableListGroup,
        subjectName: this.companyName
      };
      this.onPublishTemplateSign(publishSignDTO);
    },
    onPublishTemplateSign(publishSignDTO) {
      publishTemplateSignReq(publishSignDTO)
        .then((res) => {
          this.$message.success("操作成功");
          if (this.permissions_menu_urls.includes("/contract/elecontract")) {
            this.$router.push("/contract/elecontract");
          } else {
            this.$router.push("/contract/type");
          }
        })
        .catch((err) => {
          this.clicked = false;
          console.log("error log --> ", err);
        });
    },
    backStep() {
      this.$emit("update:variableListMap", this.variableListMap);
      this.$emit("current", 1);
    }
  }
};
</script>
<style lang="scss" scoped>
.ht .ant-modal-body {
  height: 70vh;
  overflow: auto;
}
.example {
  z-index: 999;
  width: 200px;
  height: 60px;
  position: fixed;
  top: 50%;
  left: 46%;
  .ant-spin {
    padding: 40px 60px;
    border-radius: 10px;
    background: rgba(94, 94, 94, 0.1);
  }
}
</style>
